;( function( $ ) {

var _timer_;

function login( e ) {
    e.preventDefault();

    var target = $( "#btn-login" ),
        data = {
            username: $( "#username" ).val(),
            password: $( "#pw" ).val()
        };
    
    if ( !data.username
            || data.username == "邮箱" ) {
        $( "#error" ).text( "请输入您的登录邮箱" );
        return;
    } else if ( !data.password ) {
        $( "#error" ).text( "请输入您的登录密码" );
        return;
    }

    tinyLoading.show( target );

    $.ajax({
        url: "/login/",
        type: "POST",
        data: {
            data: $.toJSON( data )
        },
        dataType: "json",
        success: function( result ){
            if ( result.success ) {
                $.cookie( "tc_un", data.username, { expires: 999 } );
                location.href = next_url;
            } else {
                tinyLoading.hide( target );
                $( "#error" ).text( "邮箱或密码错误" );

                clearTimeout( _timer_ );

                _timer_ = setTimeout( function() {
                    $( "#error" ).text( "" );
                }, 5000 );
            }
        }
    }); 
}

function fakePlaceholder() {
    var fake = $( "#fake-pw" ),
        pw = $( "#pw" );
        
    fake.show()
        .focus( function( e ) {
            $( this ).hide();
            $( "#pw" ).show().focus();
        });

	pw.hide()
	    .height( fake.height() )
        .blur( function( e ) {
            if ( $.trim( this.value ) == "" ) {
                $( this ).hide();
                $( "#fake-pw" ).show();
            }
        });

    $( "#username" ).focus( function( e ) {
		if ( this.value == "邮箱") {
			this.value = "";
		}
	}).blur( function( e ) {
        if ( $.trim( this.value ) == "" ) {
			this.value = "邮箱";
		}
    }).val( "邮箱" );
}

$( function() {
    $( ".form" ).submit( login );

    if ( !("placeholder" in document.createElement( "input" )) ) {
        fakePlaceholder();
    }

	if ( $.cookie( "tc_un" ) != null ) {
		$( "#username" ).val( $.cookie( "tc_un" ) );
		$( "#pw" ).focus();
		$( "#fake-pw" ).focus();
	}
});

})( jQuery );
